/**
 * CountDownLatch类的使用
 *
 * @author fireway
 * @since 2019年 03月 03日 星期日 06:21:42 CST
 */
package concurrency;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Waits on the CountDownLatch
 */
class WaitingTask implements Runnable {
    private static int sCounter = 0;

    private final int mId = sCounter++;

    private final CountDownLatch mLatch;

    public WaitingTask(CountDownLatch latch) {
        mLatch = latch;
    }

    @Override
    public String toString() {
        return String.format("WaitingTask %1$-3d ", mId);
    }

    @Override
    public void run() {
        try {
            mLatch.await();
            System.out.println("Latch barrier passed for " + this);
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
        }
    }
}

/**
 * Performs some portion of a task
 */
class TaskPortion implements Runnable {
    private static int sCounter = 0;

    private final int mId = sCounter++;

    private static Random sRand = new Random(47);

    private final CountDownLatch mLatch;

    public TaskPortion(CountDownLatch latch) {
        mLatch = latch;
    }

    public void doWork() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(sRand.nextInt(2000));
        System.out.println(this + "completed");
    }

    @Override
    public String toString() {
        return String.format("%1$-3d ", mId);
    }

    @Override
    public void run() {
        try {
            doWork();
            mLatch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class CountDownLatchDemo {
    private static final int SIZE = 100;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(SIZE);

        for(int i = 0; i < 10; i++) {
            exec.execute(new WaitingTask(latch));
        }

        for(int i = 0; i < SIZE; i++) {
            exec.execute(new TaskPortion(latch));
        }

        System.out.println("Launched all tasks");
        exec.shutdown(); // Quit when all tasks complete
    }
}
